<?php
namespace app\model;

 
class Comm {

static function readcomm($system,$themeid,$config) {
    global $_G, $_P;
    // $config =     Theme::getConfig($themeid);
    $theme = Theme::getById($themeid);
    if($system['fenxiao05']!=1 || $config['comm51']==0 || $config['iscomm']==0){
        return;
    }
    if ($_G['member']['uid']==$_P['fromuid'] ) {
        return;
    }



    $workerid = intval($_P['workerid']);
    $fromuid = intval($_P['fromuid']);
    $fopenid = $_P['fopenid'];
    if(!empty($fromuid) && empty($fopenid)){
        $fromfans  = Fans::getById($fromuid,$themeid);
        $fopenid = $fromfans['openid'];
    }
    if($fromuid == $_G['member']['uid'] || $fopenid == $_G['openid']){
        $fromuid = 0;
        $fopenid = "";
    }elseif($workerid>0 && $fromuid==0){
        $theyworker = Worker::getThemeWorkerByUid($workerid,$themeid,1);
        $fromuid = $theyworker['uid'];
        $fopenid = $theyworker['openid'];
    }
    if($fromuid ==0){
        return;   
    }
    // $randomfee = floatval(mt_rand($config['comm51']*100,$config['comm52']*100)/100);
    //新版概率随机
    $first = intval($config['comm53']);
    $second= $first + intval($config['comm53_2']);
    $gailv = mt_rand(0,99);
    if ($first==0 || $first==100 || $gailv < $first ) {
        $randomfee = floatval(mt_rand($config['comm51']*100,$config['comm52']*100)/100);
    }elseif ($gailv < $second && $config['comm52_2']!=0 ) {
        $randomfee = floatval(mt_rand($config['comm51_2']*100,$config['comm52_2']*100)/100);
    }elseif ($config['comm52_3']!=0 ) {
        $randomfee = floatval(mt_rand($config['comm51_3']*100,$config['comm52_3']*100)/100);
    }else{
        $randomfee = floatval(mt_rand($config['comm51']*100,$config['comm52']*100)/100);
    }

    $ClientIp = Comm::getClientIp();

    $data = array(
        'uniacid'    => $_G['mpid'],
        'themeid'    => $themeid,
        'type'       => 5,
        'uid'     => $fromuid,
        'openid'     => $fopenid,
        'fromuid'    => $_G['member']['uid'],
        'addtime'    => TIMESTAMP,
        'fee'        => $randomfee,
        'ip'    => $ClientIp,
        'status'     =>0,
    );


$theyworker = Worker::getThemeWorkerByUid($workerid,$themeid,1);

if (empty($theyworker)) {
    $workerid=0;
}elseif($theyworker['comm4status']>1){
    $workerid=0;
}elseif ($config['comm4typeyg']>0){
    $liulan = 0;
    $chengjiao = 0;
    switch ($config['comm4typeyg']) {
        case '1':
            $liulan = 30;
            break;
        case '2':
            $liulan = 40;
            break;
        case '3':
            $liulan = 50;
            break;
        case '4':
            $liulan = 60;
            break;
        case '5':
            $liulan = 70;
            break;
        case '6':
            $chengjiao = 5;
            break;
        case '7':
            $chengjiao = 10;
            break;
        case '8':
            $chengjiao = 15;
            break;
        case '9':
            $chengjiao = 20;
            break;
        case '10':
            $chengjiao = 25;
            break;
        case '11':
            $chengjiao = 30;
            break;
        case '12':
            $chengjiao = 40;
            break;
        case '13':
            $chengjiao = 50;
            break;
    }
    if ($config['forward']>500){
        if ($liulan>0) {
            if ($theyworker['forward']/$theyworker['scansum']*100 > $liulan){
                db_query("UPDATE ".tablename(t_worker)." SET comm4status = '2' WHERE uid ='{$workerid}'" );
                $workerid = 0;
            }
        }elseif ($chengjiao>0) {
            $cjtotal = db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . "
                    WHERE status > 0 and workerid = '{$workerid}' and themeid = '{$themeid}' " );
            if ($theyworker['forward'] / $cjtotal > $chengjiao){
                db_query("UPDATE ".tablename(t_worker)." SET comm4status = '2' WHERE uid ='{$workerid}'" );
                $workerid = 0;
            }
        }
    }

}
if (empty($workerid)) {
    $data['msg']='员工信息为空，无阅读红包!';
    $data['status']='9';
    $insertid = db_insert(t_commshare, $data);
    $result = array(
        "status"=>5,
        "msg"=>'员工信息为空，无红包!',
    );
    return $result;
}


$ClientIp = Comm::getClientIp();


    $begintime1 = $theme['begintime'];
    $endime1 = $theme['endtime'];
    if($begintime1 > TIMESTAMP){
        $result['errcode'] = 1;
        $result['msg'] = '活动尚未开始，敬请期待~';
        return $result;
    }
    if($endime1 < TIMESTAMP ||  $theme['status'] != 1){
        $result['errcode'] = 1;
        $result['msg'] = '活动已经结束啦，感谢您的支持';
        return $result;
    }


    //失败的提示
    $result['errcode'] = 1;
    $result['msg'] = '感谢支持!';

    // 1点-6点之前不发放
    if (date("H")<6 and date("H")>0) {
        $data['msg']='1点-6点之间不发放';
        $data['status']='10';
        $insertid = db_insert(t_commshare, $data);
        $result['errcode'] = 1;
        $result['msg'] = '感谢支持!';
        return $result;
    }

    //员工是否有红包
    if ($config['comm4worker']==1){
        $myworker = Worker::getThemeWorkerByOpenid($fopenid,$themeid,1);
        if (!empty($myworker)){
            $data['msg']='员工阅读红包关闭';
            $data['status']='11';
            $insertid = db_insert(t_commshare, $data);
            $result['errcode'] = 11;
            $result['msg'] = '感谢支持!';
            return $result;
        }
    }
    


    $fansinfo = db_find ( 'SELECT addtime,islock FROM ' . tablename ( t_fans ) . "
                WHERE uid ='{$fromuid}'" );
    if($fansinfo['islock']==1){
        $data['msg']='用户已锁定，无法领阅读红包';
        $data['status']='12';
        $insertid = db_insert(t_commshare, $data);
        return $result;
    }

    
    //检测3小时内成交数与发红包数是否达到要求
    if (!empty($config['comm4type']) || !empty($config['comm4typehb'])){
        $status= Comm::gethourslimit($themeid,$config['comm4type'],$config['comm4typehb']);
        if ($status['error']==1){
            $data['msg']=$status['msg'];
            $data['status']='8';
            $insertid = db_insert(t_commshare, $data);
            return $result;
        }
    }

    //检测今日已领的个数
    $comm5daynum= Comm::getCommyReadToday($themeid,$fromuid);
    if ($comm5daynum >= $config['comm5daynum']){
        $data['msg']='每天只可领'.$config['comm5daynum'].'个阅读红包';
        $data['status']='6';
        $insertid = db_insert(t_commshare, $data);
        $result['errcode'] = 5;
        $result['msg'] = $data['msg'];
        return $result;
    }

    //检测已领的总个数
    $comm5sum= Comm::getCommReadAll($themeid,$fromuid);
    if ($comm5sum >= $config['comm5sum']){
        $data['msg']='您总计可领'.$config['comm5sum'].'个阅读红包';
        $data['status']='7';
        $insertid = db_insert(t_commshare, $data);
        $result['errcode'] = 5;
        $result['msg'] = $data['msg'];
        return $result;
    }

    //检测每小时限额
    $Numhour= floatval(Comm::getCommshareNumHour($themeid));
    if ($Numhour>=floatval($config['comm4hour'])){
        $data['msg']='红包达小时上限';
        $data['status']='3';
        $insertid = db_insert(t_commshare, $data);
        return $result;
    }

    //检测每天限额
    $NumDay= floatval(Comm::getCommshareNumDay($themeid));
    if ($NumDay>=floatval($config['comm4day'])){
        $data['msg']='今日红包已发完';
        $data['status']='3';
        $insertid = db_insert(t_commshare, $data);
        return $result;
    }


    //检测同一IP
    if (!empty($config['comm4ip'])) {
        $NumIp= floatval(Comm::getCommshareNumIp($themeid,$ClientIp));
        if ($NumIp>=floatval($config['comm4ip'])){
            $data['msg']='同一网络到上限';
            $data['status']='4';
            $insertid = db_insert(t_commshare, $data);
            return $result;
        }
    }

    // if ($config['locationtype']==1) {
    //     $City= Comm::getCityDW($GLat, $GLng,$config['comm4city']);
    // }else{
        $City= Comm::getCity($system,$ClientIp,$config['comm4city']);
    // }

    $data['city']=$City['city'];
    
    //根据IP检测地区
    if (!empty($config['comm4city']) && $City['status']==0){
        $data['msg']='不在活动地区';
        $data['status']='2';
        $insertid = db_insert(t_commshare, $data);
        return $result;
    }

    $insertid = db_insert(t_commshare, $data);


    $weizhifulist = db_find ( 'SELECT city,fee FROM ' . tablename ( t_commshare ) . "
                WHERE themeid = '{$themeid}' and status = 0 and uid ='{$fromuid}'" );
    $weizhifu = $weizhifulist['fee'];
    if ($weizhifu>=0.3 || ($config['comm4autored']==3 && $weizhifu>0)){

        $ordersn = getMillisecond();
        $data = array(
            'uniacid'    => $_G['mpid'],
            'themeid'    => $themeid,
            'recordid'   => '',
            'ordersn'    => $ordersn,
            'type'       => 5,
            'uid'     => $fromuid,
            'openid'     => $fopenid,
            'addtime'    => TIMESTAMP,
            'fee'        => $weizhifu,
            'ip'    => $ClientIp,
            'city'    => $weizhifulist['city'],
            'fromuid'    => $_G['member']['uid'],
            'status'     =>0,
        );

        //1分钟内只能收到一个红包
        if (empty($weizhifulist['addtime'])) {
            $addtime =  TIMESTAMP - 10;
        }else{
            $addtime =  $weizhifulist['addtime'] - 10;
        }
        $p = array(':themeid' => $data['themeid'],':uid' => $data['uid'],':type' => $data['type'],':addtime' => $addtime );        
        $sql = "SELECT * FROM " . tablename (t_comm) . " WHERE themeid= :themeid and uid= :uid and type= :type and addtime > :addtime" ;
        $commrow = db_find($sql,$p);
        if (!empty($commrow)){
            db_query("UPDATE ".tablename(t_commshare)." SET status = 5, msg = '操作频繁：10秒内只能收到一个阅读红包'
                WHERE themeid = '{$themeid}' and status = 0 and uid ='{$fromuid}'" );
            $result['errcode'] = 5;
            $result['msg'] = '感谢支持';

            return $result;
        }else{          
            //将所有未支付记录更新为正常
            db_query("UPDATE ".tablename(t_commshare)." SET status = 1, sendtime = ".TIMESTAMP."
                WHERE themeid = '{$themeid}' and status = 0 and uid ='{$fromuid}'" );
        }
        

        if($system['autored']== 0 || $config['comm4autored']== 0 || ($config['comm4autored']== 2 && TIMESTAMP > $config['comm4autoredtime']) ){             
            $data['msg']='等待管理员发红包';
            $comm4tips = str_replace("#fee",$weizhifu,$config['comm4tips']);
            $result['errcode'] = 5;
            $result['msg'] = $comm4tips;
            $insertid = db_insert(t_comm, $data);
            return $result;
        }
        if($config['comm4autored']== 3){                
            $data['msg']='待客户提现';
            $insertid = db_insert(t_comm, $data);

            // $pm = array(":themeid"=>$themeid,":openid"=>$_G['openid']);
            // $totalfail = db_fetchcolumn ( 'SELECT sum(fee) FROM ' . tablename (t_comm) . ' as m 
            //             WHERE m.themeid = :themeid and status=0 and type<>99 and m.openid = :openid',$pm);
            // $totalsuccess = db_fetchcolumn ( 'SELECT sum(fee) FROM ' . tablename (t_comm) . ' as m 
            //         WHERE m.themeid = :themeid and (status=1 or status=0 and type=99) and m.openid = :openid',$pm);

            // $chae = $config['hbtixian']-$totalfail-$weizhifu;
            // if ($chae<0 || ($totalsuccess>0 && $config['hbtixianmode'] == 0)) {
            //     $comm4tips = "恭喜您获得红包" . $weizhifu . "元，可在【我的红包】中提现";
            // }else{
            //     $comm4tips = "恭喜您获得红包" . $weizhifu . "元，再有".$chae."元就可提现了";
            // }
            $result['errcode'] = 5;
            $result['msg'] = $comm4tips;
            return $result;
        }

        $totalpayfee = Order::getRealByThemeIdcomm4($themeid) + $theme['chongzhi'];
        if ($totalpayfee<0){
            $data['msg']='您的余额不足,请联系客服进行充值';
            $insertid = db_insert(t_comm, $data);
            return $result;
        }

        $insertid = db_insert(t_comm, $data);

    }else{
        $result['errcode'] = 3;
        $result['fee'] = $randomfee;
        return $result;
    }



    return; 
    //判断推荐者是不是员工
    $isworker = Worker::getThemeWorkerByOpenid($fopenid,$themeid,1);
    if (!empty($isworker)){
        $workerid = $isworker['uid'];
    }

    // $params = array();
    // $params[':openid'] = $openid;
    // $params[':themeid'] = $themeid;
    // $fans = db_find("SELECT * FROM ".tablename(t_relation)."
    //     WHERE openid = :openid and themeid = :themeid",$params);

    $data = array(
        'themeid'   => $themeid,
        'uniacid'   => $_G['mpid'],
        'uid'       => $_G['member']['uid'],
        'openid'    => $_G['openid'],
        'status'    => 1,
        'addtime'   => TIMESTAMP,
        'parentid'  => $fromuid,
        'popenid'   => $fopenid,
    );
    if ($system['hdget']==1 && Fans::getuid_old($fromuid,$themeid)) {
        $data['parentid_old']  = $fromuid;
        $data['popenid_old']  = $fopenid;
    }

}
    static function getcommssum($system,$themeid,$iscommshowfail) {
        global $_G;
        $pm = array(":themeid"=>$themeid,":openid"=>$_G['openid']);
        if ($iscommshowfail == 1 || $system['autored']==2){
            $commssum = floatval(db_fetchcolumn("SELECT sum(fee)  FROM ".tablename(t_comm)."
                WHERE themeid = :themeid and type<>99 and openid = :openid ",$pm));
        }else{
            $tfans = db_find("SELECT *  FROM ".tablename(t_fans)."
                WHERE themeid = :themeid and openid = :openid ",$pm);
            $commssum = $tfans['feesum'];
        }

        $commssum = round($commssum,2);

        //获取裂变红包未提现的金额
        if ($iscommshowfail == 1){
            $commssum2 = floatval(db_fetchcolumn("SELECT sum(fee)  FROM ".tablename(t_commshare)."
                    WHERE themeid = :themeid and openid = :openid and status = 0",$pm));
            $commssum = $commssum+round($commssum2,2);
        }
        return $commssum;   
    }

    static function getcommslist($system,$config,$themeid) {
        global $_G;
        $p = array(":themeid"=>$themeid);
        if ($system['ruanjian']==3 && $system['softstyle']==4){
            $limitnum = 30;
        }else{
            $limitnum = 10;
        }

        if ($config['iscommshowworker']==1) {

            $workerlist = db_select ( "SELECT uid FROM " . tablename ( t_worker ) );
            if (!empty($workerlist)){
                $workerkey = " and uid not in (\"" . implode(",",$workerlist) . "\")";
            }
            $workerkey = " and uid not in (";
            if (!empty( $workerlist)) {
                foreach ($workerlist as $key => $item) {
                    if ($key==0){
                        $workerkey .= $item['uid'];
                    }else{
                        $workerkey .="," . $item['uid'];
                    }
                }
            }
            $workerkey .=")";
        
        }else{
            $workerkey="";
        }

        if ($config['iscommshowfail'] == 0){
                $sql = "SELECT * FROM ".tablename(t_fans)." 
                    WHERE themeid =" . $themeid . " and feesum >0 " . $workerkey . " order by feesum desc
                          LIMIT ". $limitnum;
                $commslist = db_select($sql);
                if (!empty( $commslist)) {
                    foreach ($commslist as $index => $row){
                        $commslist[$index]['nickname'] = mb_substr($row['nickname'],0,10,'utf-8');
                    }
                }
        }else{
            $sql = "SELECT uid,sum(fee) as feesum,count(id) as commcount FROM ".tablename(t_comm)." 
                        WHERE themeid = :themeid and type <> 99  " . $workerkey . "
                        group by uid order by feesum desc limit " . $limitnum;
            $commslist = db_select($sql,$p);
            if (!empty( $commslist)) {
                foreach ($commslist as $index => $row){
                    $commfanslist = Fans::getById($row['uid'],$themeid);
                    $commslist[$index]['avatar'] = $commfanslist['avatar'];
                    $commslist[$index]['nickname'] = mb_substr($commfanslist['nickname'],0,10,'utf-8');
                }
            }
        }

        if ($config['iscommshow24']==1){
            $todaynum=strtotime(date("Y-m-d H:i:s", strtotime("-24 hour")));
            // $sql = "SELECT m.openid,sum(fee) as feesum,count(m.id) as commcount,f.avatar,f.nickname FROM ".tablename(t_comm)." as m 
            //             left join ".tablename(t_fans)." as f on f.uid = m.uid and f.themeid = m.themeid 
            //             WHERE m.themeid = :themeid and f.themeid = :themeid and m.status = 1 and m.addtime>".$todaynum."
            //             group by m.uid order by feesum desc limit 10";
            // $commslisttoday = db_select($sql,$p);
            if ($config['iscommshowfail'] == 0){
                $showfail = " and status = 1 ";
            }
            $sql = "SELECT uid,sum(fee) as feesum,count(id) as commcount FROM ".tablename(t_comm)." 
                        WHERE themeid = :themeid  and type <> 99 " . $showfail . $workerkey . "  and addtime>".$todaynum."
                        group by uid order by feesum desc limit 10";
            $commslisttoday = db_select($sql,$p);

            if (!empty( $commslisttoday)) {
                foreach ($commslisttoday as $index => $row){
                    $commfanslist = Fans::getById($row['uid'],$themeid);
                    $commslisttoday[$index]['avatar'] = $commfanslist['avatar'];
                    $commslisttoday[$index]['nickname'] = mb_substr($commfanslist['nickname'],0,10,'utf-8');
                }
            }
        }

        if (empty($config['fenxiaotip'])){
            if ($system['fenxiao01'] >0){
                if ( $system['fenxiao04'] ==1){
                    $fenxiaotip=$_G['URL']['APP_IMAGE']."fenxiao06.png";
                }elseif ( $system['fenxiao05'] ==1){
                    $fenxiaotip=$_G['URL']['APP_IMAGE']."fenxiao09.png";
                }elseif ( $system['fenxiao07'] ==1){
                    $fenxiaotip=$_G['URL']['APP_IMAGE']."fenxiao11.png";
                }else{
                    $fenxiaotip=$_G['URL']['APP_IMAGE']."fenxiao01.png";
                }
            }elseif ( $system['fenxiao04'] ==1){
                $fenxiaotip=$_G['URL']['APP_IMAGE']."fenxiao02.png";
            }elseif ( $system['fenxiao05'] ==1){
                $fenxiaotip=$_G['URL']['APP_IMAGE']."fenxiao04.png";
            }elseif ( $system['fenxiao07'] ==1){
                $fenxiaotip=$_G['URL']['APP_IMAGE']."fenxiao10.png";
            }
        }else{
            $fenxiaotip=tomedia($config['fenxiaotip']);
        }

        $result = array(
            'commslist' => $commslist,
            'commslisttoday' => $commslisttoday,
            'fenxiaotip' => $fenxiaotip
         );
        return $result;   
    }

    static function getClientIp($type = 0,$adv=true) {
        $type = $type?1:0;
        static $ip = NULL;
        if($ip !== NULL)
            return $ip[$type];
        if($adv){
            if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
                $pos = array_search('unknown',$arr);
                if(false !== $pos)
                    unset($arr[$pos]);
                $ip = trim($arr[0]);
            }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
                $ip = $_SERVER['HTTP_CLIENT_IP'];
            }elseif (isset($_SERVER['REMOTE_ADDR'])) {
                $ip = $_SERVER['REMOTE_ADDR'];
            }
        }elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        $long = sprintf("%u",ip2long($ip));
        $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
        return $ip[$type];
    }
    static function getCityDW($GLat, $GLng ,$diqu) {

        $url = "http://api.map.baidu.com/geoconv/v1/?coords=".$GLng .",".$GLat."&from=1&to=5&ak=qmTIVoEhA1bcfH1LtNWuMCa24VNqUQei";
        $json = json_decode(file_get_contents($url));
        $nGLat = ($json->result[0]->x);
        $nGLng = ($json->result[0]->y);

        $url = "http://api.map.baidu.com/geocoder/v2/?ak=qmTIVoEhA1bcfH1LtNWuMCa24VNqUQei&location=".$nGLng .",".$nGLat."&output=json&pois=0";
        $json = json_decode(file_get_contents($url));
        $result['city'] = $json->result->formatted_address;
        $dizhi = $json->result->addressComponent->province;
        $dizhi = $dizhi . $json->result->addressComponent->city;
        $dizhi = $dizhi . $json->result->addressComponent->district;
        $result['status']=0;
        // $city=$json->city;    
        // $city=str_replace('市','',$city);
        // //$city = iconv("utf-8","gb2312",$city);//字符串转码
        // $province=$json->province;
        // $province=str_replace('省','',$province);
        // //$province = iconv("utf-8","gb2312",$province);//字符串转码

        $diqu=str_replace('，',',',$diqu);
        $diqu=str_replace('|',',',$diqu);
        $diqu=str_replace(' ',',',$diqu);
        $diqu=str_replace(',,',',',$diqu);

        $diquarr=explode(',', $diqu);
        if (empty($diqu)){
            $result['status']=1;
        }elseif (!empty( $dizhi)){
            foreach ($diquarr as $index => $item){
                if (strstr( $dizhi,$item)!==false ){
                    $result['status']=1;
                    return $result;
                }
            }
        }
        return $result;
    }
    static function getCity($system,$ip,$diqu) {
        global $_G;
        $url = $system['s']['ippage'].$ip;
        // $json = json_decode(file_get_contents($url));
        // $result=Poster::getCity($system,$ip);
        $result['city'] = $_G['address']['province'].$_G['address']['city'];
        // $result['city'] = ($json->content->address);
        $result['status']=0;
        // $city=$json->city;    
        // $city=str_replace('市','',$city);
        // //$city = iconv("utf-8","gb2312",$city);//字符串转码
        // $province=$json->province;
        // $province=str_replace('省','',$province);
        // //$province = iconv("utf-8","gb2312",$province);//字符串转码

        $diqu=str_replace('，',',',$diqu);
        $diqu=str_replace('|',',',$diqu);
        $diqu=str_replace(' ',',',$diqu);
        $diqu=str_replace(',,',',',$diqu);

        $diquarr=explode(',', $diqu);
        if (empty($diqu)){
            $result['status']=1;
        }elseif (!empty($result['city'])){
            foreach ($diquarr as $index => $item){
                if (strstr($result['city'],$item)!==false ){
                    $result['status']=1;
                    return $result;
                }
            }
        }
        return $result;
    }

    static function recommedCommNotice($url,$record,$system,$nickname,$theme,$rank=1){
        global $_G, $_P;
        if(empty($system)){
            return false;
        }
        $title = "恭喜，您获得一个推荐随机红包！";
        if($rank== 2){
            $title = "恭喜，您获得一个2级推荐随机红包！";
        }
        $message = array(
            "url"       =>$url,
            "openid"    =>$record['fopenid'],
            "template_id"=>$system['notice_recommend'],
            "first"     =>$title,
            "keyword1"  =>$nickname,
            "keyword2"  =>$record['nickname'],
            "remark"    =>'感谢您的参与，点击查看活动详情,客服电话:'.$theme['mobile'],
        );
        return Message::sendTjNotice($message);
    }

    static function dealLevel2RecommendCommAfterPay($config,$record,$randomfee,$relation){
        global $_G, $_P;
        $cancomm = true;
        if($config['intheme'] == 1 ){
            $pm = array(":themeid"=>$record['themeid'],":openid"=>$record['fopenid']);
            $sql = "SELECT * FROM " . tablename (t_record) . " 
                                WHERE themeid =:themeid 
                                        and openid = :openid and status > 0 order by id desc limit 1";
            $tjrecord = db_find ($sql,$pm);
            if(!empty($tjrecord)){
                $cancomm = true;
            }else{
                $cancomm = false;
            }
        }
        if($cancomm){
            $ordersn = getMillisecond();
            $data = array(
                'uniacid'    => $record['uniacid'],
                'themeid'    => $record['themeid'],
                'recordid'   => $record['id'],
                'ordersn'    => $ordersn,
                'type'       => 2,
                'openid'     => $relation['popenid'],
                'uid'     => $relation['parentid'],
                'addtime'    => TIMESTAMP,
                'fee'        => $randomfee,
                'fopenid'    => $record['openid'],
                'fromuid'    => $record['uid'],
                'status'     =>0,
            );
            if ($system['hdget']==1) {
                if (Fans::getuid_old($relation['parentid'],$record['themeid'])) {
                    $data['uid_old']  = $relation['parentid'];
                    $data['openid_old']  = $relation['popenid'];
                }
            }
            return self::add($data);
        }else{
            return 0;
        }

    }

    static function dealLevel2RecommendCommAfterPayYixuan($config,$record,$randomfee,$relation){
        global $_G, $_P;
        $cancomm = true;
        // if($config['intheme'] == 1 ){
        //     $pm = array(":themeid"=>$record['themeid'],":openid"=>$relation['popenid']);
        //     $sql = "SELECT * FROM " . tablename (t_record) . " 
                    //             WHERE themeid =:themeid 
                    //                     and openid = :openid and status > 0 order by id desc limit 1";
        //     $tjrecord = db_find ($sql,$pm);
        //     if(!empty($tjrecord)){
        //         $cancomm = true;
        //     }else{
        //         $cancomm = false;
        //     }
        // }

        if($config['intheme'] == 1 ){
            $myworker = Worker::getThemeWorkerByOpenid($relation['popenid'],$record['themeid'],1);
            if (empty($myworker)){
                $pm = array(":themeid"=>$record['themeid'],":openid"=>$relation['popenid']);
                $sql = "SELECT * FROM " . tablename (t_record) . " 
                                    WHERE themeid =:themeid 
                                            and openid = :openid and status > 0 order by id desc limit 1";
                $tjrecord = db_find ($sql,$pm);
                if(!empty($tjrecord)){
                    $cancomm = true;
                }else{
                    $cancomm = false;
                }
            }else{
                $cancomm = true;
            }
        }
        if (floatval($config['joinfee'])>0){
            $feepay=floatval($config['joinfee']);
        }elseif (floatval($config['groupprice'])>0){
            $feepay=floatval($config['groupprice']);
        }else{
            $feepay=floatval($config['primeprice']);
        }
        if ($randomfee>=$feepay){
            $cancomm = false;
        }

        if($cancomm){
            $ordersn = getMillisecond();
            $data = array(
                'uniacid'    => $record['uniacid'],
                'themeid'    => $record['themeid'],
                'recordid'   => $record['id'],
                'ordersn'    => $ordersn,
                'type'       => 2,
                'openid'     => $relation['popenid'],
                'uid'     => $relation['parentid'],
                'addtime'    => TIMESTAMP,
                'fee'        => $randomfee,
                'fopenid'    => $record['openid'],
                'fromuid'    => $record['uid'],
                'status'     =>0,
            );
            if ($system['hdget']==1) {
                if (Fans::getuid_old($relation['parentid'],$record['themeid'])) {
                    $data['uid_old']  = $relation['parentid'];
                    $data['openid_old']  = $relation['popenid'];
                }
            }
            return self::add($data);
        }else{
            return 0;
        }

    }

    static function dealLevel3RecommendCommAfterPayYxiaun($config,$record,$randomfee,$relation){
        global $_G, $_P;
        $cancomm = true;

        // if($config['intheme'] == 1 ){
        //     $pm = array(":themeid"=>$record['themeid'],":openid"=>$relation['popenid']);//$record['fopenid']);
        //     $sql = "SELECT * FROM " . tablename (t_record) . " 
        //                         WHERE themeid =:themeid 
        //                                 and openid = :openid and status > 0 order by id desc limit 1";
        //     $tjrecord = db_find ($sql,$pm);
        //     if(!empty($tjrecord)){
        //         $cancomm = true;
        //     }else{
        //         $cancomm = false;
        //     }
        // }

        if($config['intheme'] == 1 ){
            $myworker = Worker::getThemeWorkerByOpenid($relation['popenid'],$record['themeid'],1);
            if (empty($myworker)){
                $pm = array(":themeid"=>$record['themeid'],":openid"=>$relation['popenid']);
                $sql = "SELECT * FROM " . tablename (t_record) . " 
                                    WHERE themeid =:themeid 
                                            and openid = :openid and status > 0 order by id desc limit 1";
                $tjrecord = db_find ($sql,$pm);
                if(!empty($tjrecord)){
                    $cancomm = true;
                }else{
                    $cancomm = false;
                }
            }else{
                $cancomm = true;
            }
        }
        if (floatval($config['joinfee'])>0){
            $feepay=floatval($config['joinfee']);
        }elseif (floatval($config['groupprice'])>0){
            $feepay=floatval($config['groupprice']);
        }else{
            $feepay=floatval($config['primeprice']);
        }
        if ($randomfee>=$feepay){
            $cancomm = false;
        }
        
        if($cancomm){
            $ordersn = getMillisecond();
            $data = array(
                'uniacid'    => $record['uniacid'],
                'themeid'    => $record['themeid'],
                'recordid'   => $record['id'],
                'ordersn'    => $ordersn,
                'type'       => 3,
                'openid'     => $relation['popenid'],
                'uid'     => $relation['parentid'],
                'addtime'    => TIMESTAMP,
                'fee'        => $randomfee,
                'fopenid'    => $record['openid'],
                'fromuid'    => $record['uid'],
                'status'     =>0,
            );
            if ($system['hdget']==1) {
                if (Fans::getuid_old($relation['parentid'],$record['themeid'])) {
                    $data['uid_old']  = $relation['parentid'];
                    $data['openid_old']  = $relation['popenid'];
                }
            }
            return self::add($data);
        }else{
            return 0;
        }

    }
    static function WorkerRecommendCommAfterPayYxiaun($config,$record,$randomfee){
        global $_G, $_P;
        if(empty($record['workerid'])){
            return 0;
        }
        $pm = array(":themeid"=>$record['themeid'],":uid"=>$record['workerid']);
        $sql = "SELECT * FROM " . tablename (t_worker) . " 
                  WHERE themeid =:themeid  and uid = :uid order by id desc limit 1";
        $workerinfo = db_find ($sql,$pm);

        if(!empty($workerinfo)){
            $ordersn = getMillisecond();
            $data = array(
                'uniacid'    => $record['uniacid'],
                'themeid'    => $record['themeid'],
                'recordid'   => $record['id'],
                'ordersn'    => $ordersn,
                'type'       => 6,
                'openid'     => $workerinfo['openid'],
                'uid'     => $workerinfo['uid'],
                'addtime'    => TIMESTAMP,
                'fee'        => $randomfee,
                'fopenid'    => $record['openid'],
                'fromuid'    => $record['uid'],
                'status'     =>0,
            );
            if ($system['hdget']==1) {
                if (Fans::getuid_old($workerinfo['uid'],$record['themeid'])) {
                    $data['uid_old']  = $workerinfo['uid'];
                    $data['openid_old']  = $workerinfo['openid'];
                }
            }
            return self::add($data);
        }else{
            return 0;
        }

    }

    static function dealRecommendCommAfterPay($config,$record,$randomfee){
        global $_G, $_P;
        $cancomm = true;

        if($config['intheme'] == 1 ){
            $myworker = Worker::getThemeWorkerByOpenid($record['fopenid'],$record['themeid'],1);
            if (empty($myworker)){
                $pm = array(":themeid"=>$record['themeid'],":openid"=>$record['fopenid']);
                $tjrecord = db_find ( "SELECT * FROM " . tablename (t_record) . " 
                                    WHERE themeid =:themeid 
                                            and openid = :openid and status != 0 order by id desc limit 1",$pm);
                if(!empty($tjrecord)){
                    $cancomm = true;
                }else{
                    $cancomm = false;
                }
            }else{
                $cancomm = true;
            }
        }
        if (floatval($config['joinfee'])>0){
            $feepay=floatval($config['joinfee']);
        }elseif (floatval($config['groupprice'])>0){
            $feepay=floatval($config['groupprice']);
        }else{
            $feepay=floatval($config['primeprice']);
        }
        if ($randomfee>=$feepay){
            $cancomm = false;
        }
        if($cancomm){
            $ordersn = getMillisecond();
            $data = array(
                'uniacid'    => $record['uniacid'],
                'themeid'    => $record['themeid'],
                'recordid'   => $record['id'],
                'ordersn'    => $ordersn,
                'type'       => $record['type'],
                'openid'     => $record['fopenid'],
                'uid'     => $record['fromuid'],
                'addtime'    => TIMESTAMP,
                'fee'        => $randomfee,
                'fopenid'    => $record['openid'],
                'fromuid'    => $record['uid'],
                'openid_old'     => $record['fopenid_old'],
                'uid_old'     => $record['fromuid_old'],
                'fopenid_old'    => $record['openid_old'],
                'fromuid_old'    => $record['uid_old'],
                'status'     =>0,
            );
            return self::add($data);
        }else{
            return 0;
        }

    }



    static function dealAttendCommAfterPay($record,$randomfee){
        global $_G, $_P;
        $ordersn = getMillisecond();
        $data = array(
            'uniacid'    => $record['uniacid'],
            'themeid'    => $record['themeid'],
            'recordid'   => $record['id'],
            'ordersn'    => $ordersn,
            'type'       => $record['type'],
            'openid'     => $record['openid'],
            'uid'     => $record['fromuid'],
            'addtime'    => TIMESTAMP,
            'fee'        => $randomfee,
            'fopenid'    =>$record['openid'],
            'fromuid'    =>$record['uid'],
            'status'     =>0,
        );
        return self::add($data);
    }




    static function addhbpoen($system,$config){
        global $_G,$_P;
        $p = array(':uniacid' => $_G['mpid'],':themeid' => $_P['themeid'],':uid' => $_G['member']['uid'],':type' => 10 );        
        $sql = "SELECT * FROM " . tablename (t_comm) . " WHERE uniacid= :uniacid and themeid= :themeid and uid= :uid and type= :type" ;
        $row = db_find($sql,$p);
        if (empty($row)){
            $ordersn = getMillisecond();
            $ClientIp = Comm::getClientIp();
            $City= Comm::getCity($system,$ClientIp,$config['comm4city']);
            $randomfee = floatval(mt_rand($config['hbopenfee1']*100,$config['hbopenfee2']*100)/100);
            if ($randomfee>0 && $_G['member']['uid']>0 ) {
                $data = array(
                    'uniacid'    => $_G['mpid'],
                    'themeid'    => $_P['themeid'],
                    'ordersn'    => $ordersn,
                    'type'       => 10,
                    'uid'     => $_G['member']['uid'],
                    'openid'     => $_G['openid'],
                    'fromuid'     => $_G['member']['uid'],
                    'fopenid'     => $_G['openid'],
                    'addtime'    => TIMESTAMP,
                    'fee'        => $randomfee,
                    'ip'    => $ClientIp,
                    'city'    => $City['city'],
                    'status'     =>0,
                );
                $insertid = db_insert(t_comm, $data);
                $id = $insertid;                
                return true;       
            }
        }        
        return false;
    }

    static function addhborder($system,$themeid,$config,$uid,$openid){
        global $_G,$_P; 
        $sql = "SELECT * FROM " . tablename (t_record) . "
                                    WHERE themeid =:themeid
                                            and openid = :openid and status > 0 order by id desc limit 1";
        $row = db_find($sql, array(":themeid"=>$themeid,":openid"=>$openid));

        if (!empty($row)) {
            $p = array(':uniacid' => $_G['mpid'],':themeid' => $themeid,':uid' => $uid,':type' => 11 );        
            $sql = "SELECT * FROM " . tablename (t_comm) . " WHERE uniacid= :uniacid and themeid= :themeid and uid= :uid and type= :type" ;
            $row = db_find($sql,$p);             
            if (empty($row)){
                $ordersn = getMillisecond();
                $ClientIp = Comm::getClientIp();
                $City= Comm::getCity($system,$ClientIp,$config['comm4city']);
                $randomfee = floatval(mt_rand($config['hborderfee1']*100,$config['hborderfee2']*100)/100);
                if ($randomfee>0 && $uid>0 ) {
                    $data = array(
                        'uniacid'    => $_G['mpid'],
                        'themeid'    => $themeid,
                        'type'       => 11,
                        'ordersn'    => $ordersn,
                        'uid'     => $uid,
                        'openid'     => $openid,
                        'fromuid'     => $uid,
                        'fopenid'     => $openid,
                        'addtime'    => TIMESTAMP,
                        'fee'        => $randomfee,
                        'ip'    => $ClientIp,
                        'city'    => $City['city'],
                        'status'     =>0,
                    );
                    $insertid = db_insert(t_comm, $data);
                    $id = $insertid;                
                    return true;       
                }
            }
        }     
        return false;
    }
    static function addhbtixian($system,$config,$fee){
        global $_G,$_P;
        if ($_G['member']['uid']>0 ) {
        $themeid = intval($_P['themeid']);
        $pm = array(":themeid"=>$themeid,":openid"=>$_G['openid']);
        $sql = 'SELECT id FROM ' . tablename (t_comm) . ' as m 
                WHERE m.themeid = :themeid and status=0 and type<>99 and m.openid = :openid';
        $list = db_select($sql,$pm);
        if (!empty($list)) {
            foreach ($list as $index => $row) {
                if ($index==0) {
                    $city = $row['id'];
                }else{
                    $city = $city . "," . $row['id'];
                }
                $data= array();
                $data['status']=98;
                $data['msg']="提现中";
                db_update(t_comm,$data, array('id' =>$row));
            }
            if (!empty($city)) {
                $p = array(':uniacid' => $_G['mpid'],':themeid' => $_P['themeid'],':uid' => $_G['member']['uid'],':city' => $city );  
                $sql = "SELECT * FROM " . tablename (t_comm) . " WHERE uniacid= :uniacid and themeid= :themeid and uid= :uid and city= :city" ;
                $row = db_find($sql,$p);
                if (empty($row)){
                    $ordersn = getMillisecond();
                    $ClientIp = Comm::getClientIp();
                    $data = array(
                        'uniacid'    => $_G['mpid'],
                        'themeid'    => $_P['themeid'],
                        'type'       => 99,
                        'ordersn'    => $ordersn,
                        'uid'     => $_G['member']['uid'],
                        'openid'     => $_G['openid'],
                        'fromuid'     => $_G['member']['uid'],
                        'fopenid'     => $_G['openid'],
                        'addtime'    => TIMESTAMP,
                        'fee'        => $fee,
                        'ip'    => $ClientIp,
                        'city'    => $city,
                        'status'     =>0,
                    );
                    $insertid = db_insert(t_comm, $data);
                    $id = $insertid;                
                    return $id;       
                }
            }

        }
        }
        return false;
    }

    static function add($data){
        global $_G;

        //同一个定单不可以收到多个相同类型红包
        $p = array(':uniacid' => $data['uniacid'],':themeid' => $data['themeid'],':uid' => $data['uid'],':type' => $data['type'],':recordid' => $data['recordid'] );        
        $sql = "SELECT * FROM " . tablename (t_comm) . " WHERE uniacid= :uniacid and themeid= :themeid and uid= :uid and type= :type and recordid = :recordid" ;
        $row = db_find($sql,$p);
        if (empty($row)){
            // //更新红包排行记录
            // db_query("UPDATE ".tablename(t_fans)." SET feesum = feesum + " . $data['fee'] . ", commcount = commcount + 1 WHERE uniacid = " . $data['uniacid'] ." and themeid =" . $data['themeid'] ." and uid = " . $data['uid'] );

            $insertid = db_insert(t_comm, $data);
            $id = $insertid;
        }

        return $id;
    }

    static function commRecord($comm,$system){
        global $_G;
        if(empty($comm)){
            return array("1","记录不存在");
        }
        if($comm['status']==1){
            return array("1","已经成功发放奖金");
        }

        $cachekey = 'comm2'.$_G['mpid'].MODULE_NAME.$comm['id'];
        $settings = cache_load($cachekey);
        if(!empty($settings)){
            return array("1","已尝试过发放奖金，请联系管理员");
        }
        $hassend = Trade::getByCommId($comm['id']);
        if(!empty($hassend)){
            return array("1","已经成功发放奖金@~");
        }
        $ordersn = getMillisecond();
        if ($comm['type']==4){
            $desc = '转发红包';
        }elseif ($comm['type']==6){
            $desc = '员工提成';
        }else{
            $desc = '活动赏金';
        }
        $themeid = $comm['themeid'];
        $theme = Theme::getThemeById($themeid);
        $config =   Theme::getConfig($themeid);
        if($theme['sendway']==0){
            $txresult = Util::transfer($comm['openid'],$comm['fee'],$ordersn,$desc,$system);
        }else{
            $send_name =$theme['jubf'];
            $wishing = '感谢您的支持';
            $act_name = $theme['jubf'];
            $txresult = Util::sendredpack($comm['openid'],$comm['fee'],$ordersn,$send_name,$wishing,$act_name,desc,$system);
        }
        // $settings = "commid:".$comm['id'];
        // cache_write($cachekey, $settings);
        $order = Order::getById($comm['orderid']);
        if($txresult['code'] == 0){

            $data['status']=1;
            $data['ordersn']=$ordersn;
            db_update(t_comm,$data, array('id' => $comm['id']));

            $data = array(
                'uniacid'  => $_G['mpid'],
                'ordertype'=> 'reward',
                'ordersn'  => $ordersn,
                'nickname' => $comm['nickname'],
                'avatar'   => $comm['avatar'],
                'openid'   => $comm['openid'],
                'uid'       => $comm['uid'],
                'username' => $comm['username'],
                'mobile'   => $comm['mobile'],
                'addtime'  => TIMESTAMP,
                'orderfee' => $comm['fee']*(-1),
                'theme'    => $theme['title'],
                'paystate'=> 1,
                'paytime' => TIMESTAMP,
                'status'  => 1,
                'type'    => 'wechat',
                'realfee' => $comm['fee']*(-1),
            );
            $tid = '1'.$ordersn;
            $data['masterid']  = $comm['orderid'];
            $data['detailid']  = $comm['id'];
            $data['themeid']   = $comm['themeid'];
            $data['tid'] = $tid;
            db_insert (t_trade,$data);
            $id = $insertid;
            if($id <= 0){
                return array("1","定单数据错误");
            }
            if($system['noticeopen'] == 1){
                $url2 = $_G['siteroot'].'app/index.php?i='.$_G['mpid'].'&c=entry&themeid='.$themeid.'&do=index&m=order';

                if($comm['type']== 0){
                    $first = $comm['username'].'您好，您参团获得的赏金已经成功发放！';
                }elseif ($comm['type']== 1){
                    $first = $comm['username'].'您好，您推荐【'.$order['username'].'】的赏金已成功发放！';
                }else{
                    $first = $comm['username'].'您好，来自推荐【'.$order['username'].'】的赏金已成功发放！';
                }
                $message = array(
                    "url"       =>$url2,
                    "openid"    =>$comm['openid'],
                    "first"     =>$first,
                    "keyword1"  =>'￥'.$comm['fee'],
                    "keyword2"  =>'提现到微信余额',
                    "keyword3"  =>date('Y-m-d  H:i:s',$comm['addtime']),
                    "keyword4"  =>'审核通过',
                    "keyword5"  =>date('Y-m-d H:i:s'),
                    "remark"    =>'感谢您的参与，点击查看活动详情,客服电话:'.$theme['tel'],
                );
                $r = Util::sendCommNotice($message,$system);
            }
            return array("0","发放成功");
        }else{
            db_update(t_comm,array("msg"=>$txresult['message']), array('id' => $comm['id']));
            return array("1",'失败：'.$txresult['message']);
        }
    }

    static function getById($id) {
        if (empty($id)) {
            return false;
        }
        $sql = "SELECT * FROM " . tablename(t_comm) . " where id = :id";
        $row = db_find($sql, array(":id"=>$id));
        return $row;
    }

    static function getUnPayList(){
        global $_G, $_P;
        $list = db_select( "SELECT * FROM " . tablename (t_comm) . " WHERE  status = 0 order by id limit 1" );
        return $list;
    }

    static function getCommtixian($id) {
        global $_G, $_P;
        $sql = "SELECT * FROM " . tablename (t_comm) . " WHERE id = " .$id . " limit 1" ;
        $row = db_find($sql);
        $row['sql'] = $sql;
        $row['param'] =$p;
        return $row;
    }
    
    static function getCommZhuanfa($commRecord) {
        global $_G, $_P;
        $p = array(':themeid' => $commRecord['themeid'],':uid' => $commRecord['uid'],':addtime' => $commRecord['addtime']);
        $sql = "SELECT * FROM " . tablename (t_comm) . " WHERE themeid= :themeid and uid= :uid and addtime= :addtime and type=4 limit 1" ;
        $row = db_find($sql,$p);
        $row['sql'] = $sql;
        $row['param'] =$p;
        return $row;
    }

    static function getCommyaoyiyao($commRecord) {
        global $_G, $_P;
        $p = array(':themeid' => $commRecord['themeid'],':uid' => $commRecord['uid'],':addtime' => $commRecord['addtime']);
        $sql = "SELECT * FROM " . tablename (t_comm) . " WHERE themeid= :themeid and uid= :uid and addtime= :addtime and type=7 limit 1" ;
        $row = db_find($sql,$p);
        $row['sql'] = $sql;
        $row['param'] =$p;
        return $row;
    }
    
    //检查是否已有转发红包
    static function getIsCommZhuanfa($commRecord) {
        global $_G, $_P;
        $p = array(':uid' => $commRecord['uid']);
        $sql = "SELECT * FROM " . tablename (t_comm) . " WHERE uid= :uid and (type=4 or type=7) limit 1" ;
        $row = db_find($sql,$p);
        if (empty($row)){
            return true;
        }else{
            return false;
        }
    }


    //检查是否已有转发红包
    static function getCommshareTime($themeid,$fuid) {
        global $_G, $_P;
        $sql = "SELECT * FROM " . tablename (t_commshare) . " WHERE themeid=".$themeid." and uid=".$fuid." and type=4 and status<2 order by addtime desc limit 1" ;
        $row = db_find($sql);
        if (empty($row)){
            return 1000000;
        }else{
            return intval((TIMESTAMP - $row['addtime'])/60);
        }
    }
    
    //在服务器别的软件领过的不可以领
    static function gethistorycomm($themeid) {
        global $_G;
        //获取裂变红包的总个数，低于50个不限制
        $condition="themeid=".$themeid." and (type=4 or type=7) ";
        $comm4count = db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_comm ) . " 
                    WHERE  {$condition} " );
        if ($comm4count<50) {
            $status['error'] = 0;
        }else{
            $today=strtotime("-3 month");
            $commlist = db_find ( 'SELECT * FROM ' . tablename ( '2019comm_list' ) . "
                    WHERE openid = '" . $_G['openid'] . "' and software!='" . MODULE_NAME ."' and addtime>".$today);
            if (empty($commlist)){
            }else{
                $status['error'] = 1;
                $status['msg'] = '此用户' . date('Y-m-d  H:i:s',$commlist['addtime']) . '在活动' . $commlist['software'] .'中领过红包';
            }
        }
        
        return $status;
    }


    //检测3小时内的发放红包数与成交单数
    static function gethourslimit($themeid,$type,$typehb) {
        global $_G;
        //获取裂变红包的总个数，低于50个不限制
        $condition="themeid=".$themeid." and (type=4 or type=7) ";
        $comm4count = db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_comm ) . " 
                    WHERE  {$condition} " );
        if ($comm4count<50) {
            $status['error'] = 0;
        }else{
            $today=strtotime("-3 hour");
            $condition="themeid=".$themeid." and (type=4 or type=7) and addtime>".$today;
            $comm4fee = db_fetchcolumn ( 'SELECT sum(fee) FROM ' . tablename ( t_comm ) . " 
                        WHERE  {$condition} " );
            $comm4fee = sprintf("%.2f", $comm4fee);

            $orderfee = db_fetchcolumn ( 'SELECT sum(realfee) FROM ' . tablename ( t_order ) . "
                    WHERE themeid = '{$themeid}' and paystate = 1 and realfee > 0 and addtime>".$today);
            $orderfee = sprintf("%.2f", $orderfee);

            $ordercount = db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . "
                    WHERE themeid = '{$themeid}' and status > 0  and status!=3 and addtime>".$today);

            $status['error'] = 0;
            if ($type == 1 && $ordercount==0) {
                $status['error'] = 1;
                $status['msg'] = '最近3小时成交了'.$ordercount.'单，红包已停发';
            } elseif ($type == 2 && $ordercount < 2) {
                $status['error'] = 1;
                $status['msg'] = '最近3小时成交了'.$ordercount.'单，小于2单红包已停发';
            } elseif ($type == 3 && $ordercount < 3) {
                $status['error'] = 1;
                $status['msg'] = '最近3小时成交了'.$ordercount.'单，小于3单红包已停发';
            } elseif ($type == 4 && $ordercount < 5) {
                $status['error'] = 1;
                $status['msg'] = '最近3小时成交了'.$ordercount.'单，小于5单红包已停发';
            } elseif ($type == 5 && $ordercount < 10) {
                $status['error'] = 1;
                $status['msg'] = '最近3小时成交了'.$ordercount.'单,小于10单红包已停发';
            } elseif ($type == 6 && $ordercount < 20) {
                $status['error'] = 1;
                $status['msg'] = '最近3小时成交了'.$ordercount.'单,小于20单红包已停发';
            } 

            if ($typehb == 1 && $comm4fee>=$orderfee) {
                $status['error'] = 1;
                $status['msg'] = '最近3小时收入'.$orderfee.'元，裂变红包'.$comm4fee.'元,超限已停发';
            } elseif ($typehb == 2 && $comm4fee>=$orderfee+20) {
                $status['error'] = 1;
                $status['msg'] = '最近3小时收入'.$orderfee.'元，裂变红包'.$comm4fee.'元,超20元已停发';
            } elseif ($typehb == 3 && $comm4fee>=$orderfee+50) {
                $status['error'] = 1;
                $status['msg'] = '最近3小时收入'.$orderfee.'元，裂变红包'.$comm4fee.'元,超50元已停发';
            } elseif ($typehb == 4 && $comm4fee>=$orderfee+100) {
                $status['error'] = 1;
                $status['msg'] = '最近3小时收入'.$orderfee.'元，裂变红包'.$comm4fee.'元,超100元已停发';
            } elseif ($typehb == 5 && $comm4fee>=$orderfee+200) {
                $status['error'] = 1;
                $status['msg'] = '最近3小时收入'.$orderfee.'元，裂变红包'.$comm4fee.'元,超200元已停发';
            }
        }
        return $status;
    }

    //检测今日已领的个数-阅读红包
    static function getCommyReadToday($themeid,$fuid) {
        global $_G;
        $todaynum=strtotime(date('Y-m-d'.'00:00:00',time()));
        $condition="themeid=".$themeid." and uid=".$fuid." and type=5 and status<2 and addtime>".$todaynum;
        return db_fetchcolumn ( 'SELECT count(*) FROM ' . tablename ( t_commshare ) . " 
                    WHERE  {$condition} " );
    }
    

    //检测已领的总个数-阅读红包
    static function getCommReadAll($themeid,$fuid) {
        global $_G;
        $todaynum=strtotime(date('Y-m-d'.'00:00:00',time()));
        $condition="themeid=".$themeid." and uid=".$fuid." and type=5 and status<2";
        return db_fetchcolumn ( 'SELECT count(*) FROM ' . tablename ( t_commshare ) . " 
                    WHERE  {$condition} " );
    }


    //检测今日已领的个数
    static function getCommshareToday($themeid,$fuid) {
        global $_G;
        $todaynum=strtotime(date('Y-m-d'.'00:00:00',time()));
        $condition="themeid=".$themeid." and uid=".$fuid." and (type=4 or type=7) and status<2 and addtime>".$todaynum;
        return db_fetchcolumn ( 'SELECT count(*) FROM ' . tablename ( t_commshare ) . " 
                    WHERE  {$condition} " );
    }
    

    //检测已领的总个数
    static function getCommshareAll($themeid,$fuid) {
        global $_G;
        $todaynum=strtotime(date('Y-m-d'.'00:00:00',time()));
        $condition="themeid=".$themeid." and uid=".$fuid." and (type=4 or type=7) and status<2";
        return db_fetchcolumn ( 'SELECT count(*) FROM ' . tablename ( t_commshare ) . " 
                    WHERE  {$condition} " );
    }


    //获取今天的转发红包个数
    static function getCommNumDay($themeid) {
        global $_G;
        $todaynum=strtotime(date('Y-m-d'.'00:00:00',time()));
        $condition="themeid=".$themeid." and (type=4 or type=7) and addtime>".$todaynum;
        return db_fetchcolumn ( 'SELECT sum(fee) FROM ' . tablename ( t_comm ) . " 
                    WHERE  {$condition} " );
    }

    static function getCommshareNumDay($themeid) {
        global $_G;
        $todaynum=strtotime(date('Y-m-d'.'00:00:00',time()));
        $condition="themeid=".$themeid." and (type=4 or type=5 or type=7) and status<2 and addtime>".$todaynum;
        return db_fetchcolumn ( 'SELECT sum(fee) FROM ' . tablename ( t_commshare ) . " 
                    WHERE  {$condition} " );
    }

    static function getCommshareNumHour($themeid) {
        global $_G;
        $todaynum=strtotime(date('Y-m-d H'.':00:00',time()));
        $condition="themeid=".$themeid." and (type=4 or type=5 or type=7) and status<2 and addtime>".$todaynum;
        return db_fetchcolumn ( 'SELECT sum(fee) FROM ' . tablename ( t_commshare ) . " 
                    WHERE  {$condition} " );
    }


    //获取当前IP的转发红包个数
    static function getCommNumIp($themeid,$ip) {
        global $_G;
        $condition="themeid=".$themeid." and (type=4 or type=5 or type=7)  and ip='".$ip."'";
        return db_fetchcolumn ( 'SELECT sum(fee) FROM ' . tablename ( t_comm ) . " 
                    WHERE  {$condition} " );
    }

    //获取当前IP的转发红包个数
    static function getCommshareNumIp($themeid,$ip) {
        global $_G;
        $condition="themeid=".$themeid." and (type=4 or type=5 or type=7) and status<2 and ip='".$ip."'";
        return db_fetchcolumn ( 'SELECT sum(fee) FROM ' . tablename ( t_commshare ) . " 
                    WHERE  {$condition} " );
    }

    static function getUnPayOneItem() {
        global $_G, $_P;
        $sql = "SELECT * FROM " . tablename (t_comm) . " WHERE msg IS NULL and type<4 order by id limit 1" ;
        $row = db_find($sql);
        $row['sql'] = $sql;
        return $row;
    }
    static function getUnPayOneItemNew($system,$themeid) {
        global $_G, $_P;
        if ($system['autored']==1){
            $p = array(':themeid' => $themeid);
            $sql = "SELECT * FROM " . tablename (t_comm) . " WHERE themeid= :themeid and type!=10 and type!=11 and type!=99 and (msg IS NULL) order by id limit 1" ;
            $row = db_find($sql,$p);
            
            if (empty($row)) {
                $sql = "SELECT * FROM " . tablename (t_comm) . " WHERE themeid= :themeid and type!=10 and type!=11 and type!=99 and (msg IS NULL or msg = '-2:余额不足' or msg = '-2:系统繁忙，请稍后再试' ) and status=0 order by id limit 1" ;
                $row = db_find($sql,$p);
            }
            $data = array();
            $data['msg']="系统自动发放中";
            db_update(t_comm,$data, array('id' => $row['id']));            
            return $row;
        }elseif ($system['autored']==2) {           
            $p = array(':themeid' => $themeid);
            $sql = "SELECT * FROM " . tablename (t_comm) . " WHERE themeid= :themeid and (msg IS NULL) and type =99 order by id limit 1" ;
            $row = db_find($sql,$p);
            
            if (empty($row)) {
                $sql = "SELECT * FROM " . tablename (t_comm) . " WHERE themeid= :themeid and (msg IS NULL or msg = '-2:余额不足' or msg = '-2:系统繁忙，请稍后再试' ) and type =99 and status=0 order by id limit 1" ;
                $row = db_find($sql,$p);
            }
            $data = array();
            $data['msg']="系统自动发放中";
            db_update(t_comm,$data, array('id' => $row['id']));            
            return $row;
        }
    }

    static function getFeeRank($themeid){
        $p = array(":themeid"=>$themeid);

        $sql = "SELECT m.openid,m.uid,sum(fee) as feesum,count(m.id) as commcount,f.avatar,f.nickname FROM ".tablename(t_comm)." as m
                            left join ".tablename(t_member)." as f on f.openid = m.openid
                WHERE m.themeid = :themeid and m.status = 1 group by m.openid,m.uid order by feesum desc limit 20";

        $commslist = db_select($sql,$p);
        return $commslist;
    }

    static function getFeeSum($openid,$themeid) {
        if (empty($openid)) {
            return false;
        }
        $pm = array(":themeid"=>$themeid,":openid"=>$openid);
        $sql = "SELECT sum(fee)  FROM ".tablename(t_comm)."
                WHERE themeid = :themeid and openid = :openid and status = 1";
        $commssum = floatval(db_fetchcolumn($sql,$pm));
        return $commssum;
    }

    static function deleteById($id){
        if (empty($id)) {
            return false;
        }
        db_delete ( t_comm, array ('id' => $id) );
        return true;
    }


    static function getListByCondition($condition,$pageNumber,$pageSize){
        $sql = "SELECT master.*,t.title as theme,tt.nickname as fnickname,tt.avatar as favatar,tt.username as fusername,tt.mobile as fmobile FROM " . tablename ( t_comm ) . " as master
                        left join " . tablename ( t_theme ) . " as t on t.id = master.themeid
                        left join " . tablename ( t_order ) . " as tt on tt.id = master.orderid
                        WHERE   {$condition} ORDER BY master.id desc
                                    LIMIT " . ($pageNumber - 1) * $pageSize . ',' . $pageSize;
        $list = db_select ( $sql );
        return $list;

    }

    static function getIncomeByThemeId($themeid){
        $income = db_fetchcolumn ( 'SELECT sum(realfee) FROM ' . tablename ( t_comm ) . "
                WHERE themeid = :themeid and paystate = 1 and ordertype = 'theme' and orderfee > 0 ", array(":themeid"=>$themeid) );
        return floatval($income);
    }

    static function getOutcomeByThemeId($themeid){
        $income = db_fetchcolumn ( 'SELECT sum(realfee) FROM ' . tablename ( t_comm ) . "
                WHERE themeid = :themeid and paystate = 1 and ordertype = 'comm' and orderfee < 0 ", array(":themeid"=>$themeid) );
        return floatval($income);
    }


    static function getNumByCondition($condition){
        return db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_comm ) . " as master
                    WHERE  {$condition} ORDER BY master.id" );

    }

    static function getListByThemeIdNew($themeid,$limit = 50,$danmu02,$danmu03,$danmu04) {
        if (empty($themeid)) {
            return false;
        }
        $condition = "";
        if ($danmu02 == 1) {
            $condition = $condition . " and cm.type>3 and cm.type <> 9 ";
        }
        if ($danmu03 == 1) {
            $condition = $condition . " and cm.type <> 6 ";
        }
        if ($danmu04 == 1) {
            $condition = $condition . " and cm.type <> 4 and cm.type <> 5 and cm.type <> 7 ";
        }
        $sql = "SELECT cm.*,f.nickname,f.uid as fansuid,f.avatar,d.username,d.nickname as n2 FROM ".tablename(t_comm)." as cm
                                left join ".tablename(t_record)." as d on d.id = cm.recordid
                                        left join ".tablename(t_fans)." as f on f.openid = cm.openid and f.themeid = cm.themeid
                                    WHERE cm.themeid = :themeid " . $condition . " order by cm.id desc limit ".$limit ;
        $commlist = db_select ( $sql, array(":themeid"=>$themeid));
        return $commlist;
    }
    static function getListByThemeId($themeid,$limit = 50) {
        if (empty($themeid)) {
            return false;
        }
        $sql = "SELECT cm.*,f.nickname,f.avatar,d.username,d.nickname as n2 FROM ".tablename(t_comm)." as cm
                                left join ".tablename(t_record)." as d on d.id = cm.recordid
                                        left join ".tablename(t_fans)." as f on f.openid = cm.openid and f.themeid = cm.themeid
                                    WHERE cm.themeid = :themeid order by cm.id desc limit ".$limit ;
        $commlist = db_select ( $sql, array(":themeid"=>$themeid));
        return $commlist;
    }

    static function getCommByOpenId($id,$openid) {
        if (empty($id)) {
            return false;
        }
        $sql = "SELECT * FROM " . tablename(t_comm) . " 
                        where  openid = :openid and paystate = 1 and ordertype = 'comm' order by id desc";
        $row = db_select($sql, array(":openid"=>$openid));
        return $row;
    }


    static function getCommNumByOpenid($openid,$uniacid){
        $params = array();
        $params[':openid'] = $openid;
        $point = db_fetchcolumn("SELECT count(*) FROM ".tablename(t_comm)."
            WHERE openid = :openid and paystate = 1 and ordertype ='comm'",$params);
        return intval($point);
    }

    static function getOrderSumByOpenid($openid,$uniacid){
        $params = array();
        $params[':openid'] = $openid;
        $point = db_fetchcolumn("SELECT count(*) FROM ".tablename(t_comm)."
            WHERE openid = :openid and status >= 0",$params);
        return intval($point);
    }

    static function getByPaystateOrderId($id) {
        if (empty($id)) {
            return false;
        }
        $sql = "SELECT * FROM " . tablename(t_comm) . " 
                        where orderid = :id and paystate = 1 and ordertype = 'repair' order by id desc";
        $row = db_find($sql, array(":id"=>$id));
        return $row;
    }
    static function getByOrderIdAndOpenid($themeid,$orderid,$openid) {
        if (empty($openid) || empty($orderid) || empty($themeid)) {
            return false;
        }
        $sql = "SELECT * FROM " . tablename(t_comm) . " 
                        where themeid = :themeid and masterid = :masterid and openid = :openid 
                                and orderfee > 0 and ordertype = 'theme' order by id desc limit 1";
        $row = db_find($sql, array(":themeid"=>$themeid,":masterid"=>$orderid,":openid"=>$openid));
        return $row;
    }
    static function getByOrderId($id,$openid) {
        if (empty($id)) {
            return false;
        }
        $sql = "SELECT * FROM " . tablename(t_comm) . " 
                        where orderid = :id and openid = :openid and paystate = 1 and ordertype = 'order' order by id desc";
        $row = db_find($sql, array(":id"=>$id,":openid"=>$openid));
        return $row;
    }
    static function getByMixId($openid,$orderid,$uniacid){
        if (empty($openid) || empty($orderid) || empty($uniacid)) {
            return false;
        }
        $sql = "SELECT * FROM " . tablename(t_comm) . " 
                        where openid = :openid and orderid =:orderid  order by id desc";
        $row = db_find($sql, array(":openid"=>$openid,":orderid"=>$orderid));
        return $row;

    }
}
?>